<?php
namespace Personnelsystem\Controller;
use Think\Controller;
use Think\Upload;
use Think\Page;
require('lib/PHPExcel.php');
require('lib/PHPExcel/IOFactory.php');

define('LG','cn');  //定死语言是汉语

ob_end_clean();
header("content-type:text/html;charset=utf-8");
class StaffController extends LoginTrueController {

    public function Add(){
        $this->LoginTrue();
        $this->LoginAreaAdmin();
        $staffNum=M("staff");
        $department=M("department");
        $rs_staffNum=$staffNum->count();
        $number=$rs_staffNum+1;
        $this->assign("number",$number);
        //村组的处理
        $regione1=session('regione1');
        $regione2=session('regione2');
        $regione3=session('regione3');
        $regione4=session('regione4');

        if(count($regione4)==1){
            $regioneid=$regione4[0]['id'];
            $xiaozulist=$department->field('dId,dName')->where("pId='{$regioneid}'")->select();
        }
        //下面对自定义变量的处理
        $variables=M("variables");

        $rs_minzu = $variables->where("vId=5")->find();  //处理民族
		$minzuval=unserialize(stripslashes($rs_minzu["vVariablesVal"]));
        $minzu = $minzuval[LG];
        $this->assign("minzu", $minzu);

        $this->assign("regione1",$regione1);
        $this->assign("regione2",$regione2);
        $this->assign("regione3",$regione3);
        $this->assign("regione4",$regione4);
        $this->assign("xiaozulist",$xiaozulist);
        $this->display();
    }
    public function up(){
        $config = array(
            'rootPath'      =>  './Uploads/', //保存根路径
            'savePath'      =>  'Staff/photo/', //保存路径
            'subName' =>array('date','Ymd'),
        );
        $up=new \Think\Upload($config);
        $rup=$up->upload($_FILES);
        $a="";
        foreach($rup as $v){
            $name='./Uploads/'.$v['savepath'].$v['savename'];
            $url='Uploads/'.$v['savepath'].$v['savename'];
            list($width, $height, $type, $attr) = getimagesize($name);
            if($width > 0){
                echo json_encode(array("error"=>"0","pic"=>$url));
            }else{
                echo json_encode(array("error"=>"上传有误，清检查服务器配置！"));
            }
        }
    }
    public function AddAction(){
        $this->LoginAreaAdmin();
        $this->LoginTrue();
        $staffAdd=M("staff");
        $yinsu=$_POST["yinsu"];
        $string=implode(",",$yinsu);
        $data["stYinsuyuan"]=$string;
        $data["stName"]=$_POST["stName"];
        $data["stSex"]=$_POST["stSex"];
        $data["stTel"]=$_POST["stTel"];
		
		$data["nationNanme"]=$_POST["nationNanme"];	//民语名字
		$data["maisonNum"]=$_POST["maisonNum"];	//房屋编号
		$data["xiaozu"]=$_POST["xiaozu"];	//小组
		$data["regioneNum"]=$_POST["regione4"];	//行政区划代码
		
        $data["stMultiracial"]=$_POST["stMultiracial"];	//名族
        if($data["stMultiracial"]==""){
            $data["stMultiracial"]="汉族";
        }

        $data["stPhoto"]=$_POST["stPhoto"];		//照片
        if($data["stPhoto"]==""){
            $data["stPhoto"]="0";
        }
        $data["stIDCard"]=$_POST["stIDCard"];		//身份证
        if($data["stIDCard"]==""){
            $data["stIDCard"]="";
        }else{
            $rs_stID=$staffAdd->select();
            foreach($rs_stID as $val_stID){
                if($data["stIDCard"]==$val_stID["stIDCard"]){
                    if($data["stIDCard"]!=""){
                    $this->error("此身份证号码已经存在");
                    }
                }
            }
        }

        $data["stInputDate"]=time();
        $result=$staffAdd->add($data);
        if($result){
            $this->success("录入人员信息成功",U("lists"));
        }else{
            $this->error("录入人员信息失败");
        } 
    }

    /**
     * //批量增加用户
     */
    public function batchAddAction(){
        $this->LoginAreaAdmin();
        $this->LoginTrue();
        $staffAdd=M("staff");
		$regione=M("regione");
		$department=M("department");
        $excel=$_FILES["excel"];  //批量人员excel表
		$objPHPExcelReader = \PHPExcel_IOFactory::load($excel["tmp_name"]);  //加载excel文件
        foreach($objPHPExcelReader->getWorksheetIterator() as $sheet)  //循环读取sheet
		{
			foreach($sheet->getRowIterator() as $row)  //逐行处理
			{
				if($row->getRowIndex()<2)  //确定从哪一行开始读取
				{
					continue;
				}
				foreach($row->getCellIterator() as $cell)  //逐列读取
				{
					
					$val=$cell->getValue();
					if(is_object($val))  $val= $val->__toString();

					if($cell->getColumn()=='A')
					{
						if(!empty($val)){
							$data[$row->getRowIndex()]['stName'] = $val; //姓名
						}else{
							continue;
						}
					}
					if($cell->getColumn()=='B')
					{
						if(!empty($val)){
							$data[$row->getRowIndex()]['nationNanme'] = $val; //民语姓名
						}
					}
					if($cell->getColumn()=='C')
					{
						if(!empty($val)){
							$data[$row->getRowIndex()]['stSex'] = $val; //性别
						}
					}
					if($cell->getColumn()=='D')
					{
						if(!empty($val)){
							$staffinfo=$staffAdd->where("stIDCard='{$val}'")->find();
							if(!empty($staffinfo)){
								$this->error("用户身份证号： ".$val."  在系统中已存在");
							}
							$data[$row->getRowIndex()]['stIDCard'] = $val; //身份证号
						}
					}
					if($cell->getColumn()=='E')
					{
						if(!empty($val)){
							$regioneinfo=$regione->where("id='{$val}'")->find();
							if(empty($regioneinfo)){
								$this->error("行政区划代码： ".$val."  不存在系统中，请检查是否正确");
							}
							$data[$row->getRowIndex()]['regioneNum'] = $val; //行政区划代码
						}
					}
					if($cell->getColumn()=='F')
					{
						if(!empty($val)){
							$departmentinfo=$department->where("dName='{$val}'")->find();
							if(empty($departmentinfo)){
								$this->error("小组： ".$val."  不存在系统中，请检查是否正确");
							}
							$data[$row->getRowIndex()]['xiaozu'] = $departmentinfo['dId']; //小组
						}
					}
					if($cell->getColumn()=='G')
					{
						if(!empty($val)){
							$data[$row->getRowIndex()]['maisonNum'] = $val; //房屋编号
						}
					}
	
				}
			}
		}
		$i=0;
		foreach($data as $key => $val){
			$result=$staffAdd->add($val);
			if($result){
				$i++;	
			}else{
				$this->error("录入 ".$val['stName']." 时失败");
				exit;
			}
		}
		$this->success("成功录入".$i."人",U("lists"));
    }
	
    public function Lists(){
        $this->LoginTrue();
        $staffLists=M("staff");
        $regione=M("regione");
        $department=M("department");
        $lib=new LibController();

        $stName=$_POST["stName"];  //姓名查询
        $stSex=$_POST["stSex"];  //性别查询
        $stIDCard=$_POST["stIDCard"];  //身份证查询
        $xiaozu=$_POST["xiaozu"];  //小组查询

        $where=" stId > 0 ";
        if(empty($_POST["regione1"])){
            $regione1=$regione->where("pId='650000000000'")->select();
        }
        $regioneid=$_POST["regione1"];  //地区查询
        if(!empty($_POST["regione2"])){
            $regioneid=$_POST["regione2"];
        }
        if(!empty($_POST["regione3"])){
            $regioneid=$_POST["regione3"];
        }
        if(!empty($_POST["regione4"])){
            $regioneid=$_POST["regione4"];
        }
        if(!empty($xiaozu)){
            $xiaozuInfo=$department->field('pId')->where("dId=$xiaozu")->find();
            $regioneid=$xiaozuInfo['pId'];
        }

        $regione_list=$regione->select();//获取所有地区

        if(!empty($regioneid)){     //如果地区查询，且没选择小组

            if(empty($xiaozu)){
                $lib->relist=$regioneid;
                $lib->createtree($regione_list,$regioneid);
                $where.="and regioneNum in($lib->relist)";
            }

            $lib->getFatherRegione($regione_list,$regioneid);
            $flagFn=$fn=count($lib->father_Regione);
            for($fn ;$fn>0;$fn--){
                if($fn==1){
                    $regione1=session('regione1');
                    //$regione1[]=$lib->father_Regione[$flagFn-1];
                    if($flagFn==1){
                        $pId=$lib->father_Regione[$flagFn-1]['id'];
                        $regione2=$regione->where("pId=$pId")->select();
                    }
                }
                if($fn==2){
                    if(!empty(session('regione2'))){
                        $regione2=session('regione2');
                    }else{
                        $regione2=$regione->where("pId='{$_POST['regione1']}'")->select();
                    }
                    if($flagFn==2){
                        $pId=$lib->father_Regione[$flagFn-2]['id'];
                        $regione3=$regione->where("pId=$pId")->select();
                    }
                }
                if($fn==3){
                    if(!empty(session('regione3'))){
                        $regione3=session('regione3');
                    }else{
                        $regione3=$regione->where("pId='{$_POST['regione2']}'")->select();
                    }
                    if($flagFn==3){
                        $pId=$lib->father_Regione[$flagFn-3]['id'];
                        $regione4=$regione->where("pId=$pId")->select();
                    }
                }
                if($fn==4){
                    if(!empty(session('regione4'))){
                        $regione4=session('regione4');
                    }else{
                        $regione4=$regione->where("pId='{$_POST['regione3']}'")->select();
                    }
                    if($flagFn==4){
                        $pId=$lib->father_Regione[$flagFn-4]['id'];
                        $xiaozulist=$department->field('dId,dName')->where("pId=$pId")->select();
                    }
                }
            }
        }else{
            $regione1=session('regione1');
            $regione2=session('regione2');
            $regione3=session('regione3');
            $regione4=session('regione4');

            if(count($regione4)==1){
                $regioneid=$regione4[0]['id'];
                $xiaozulist=$department->field('dId,dName')->where("pId='{$regioneid}'")->select();
            }
            $lib->relist=session('manageRegione');
            $lib->createtree($regione_list,session('manageRegione'));
            $where.="and regioneNum in($lib->relist)";
        }

        if(!empty($stName)){   		//如果查询姓名
            $where.=" and stName LIKE '%{$stName}%'";
        }
        if(!empty($stIDCard)){		//如果查询身份证
            $where.=" and stIDCard='{$stIDCard}'";
        }
        if(!empty($stSex)){		//如果查询性别
            $where.=" and stSex='{$stSex}'";
        }
        if(!empty($xiaozu)){		//如果查询小组
            $where.=" and xiaozu='{$xiaozu}'";
        }

        //处理分页
        if($_POST['page']){
            $pageid=$_POST['page']-1;
            $_GET['p']=$_POST['page'];
        }else
            $pageid=0;
        $count = $staffLists->where($where)->count();// 查询满足要求的总记录数 $map表示查询条件
        $Page = new Page($count,10);// 实例化分页类 传入总记录数  没也显示10条
        $Page->rollPage=7;
        $Page -> setConfig('header','<div class="sum">共%TOTAL_ROW%条</div>');
        $Page -> setConfig('first','首页');
        $Page -> setConfig('last','尾页');
        $Page -> setConfig('prev','上一页');
        $Page -> setConfig('next','下一页');
        $show = $Page->show();// 分页显示输出
        $this->assign('page',$show);// 赋值分页输出

        $rs_staffLists=$staffLists->where($where)->order('stId desc')->select();

        if($_POST["isDownload"]){
            $this->getExcel($rs_staffLists);
        }

        $this->assign("rs_staffLists",array_slice($rs_staffLists,$pageid*10,10));

        $this->assign("stName",$_POST["stName"]);
        $this->assign("stIDCard",$_POST["stIDCard"]);
        $this->assign("stSex",$_POST["stSex"]);
        $this->assign("xiaozu",$_POST["xiaozu"]);

        $this->assign("regione1",$regione1);
        $this->assign("regione2",$regione2);
        $this->assign("regione3",$regione3);
        $this->assign("regione4",$regione4);
        $this->assign("regione1id",$_POST['regione1']);
        $this->assign("regione2id",$_POST['regione2']);
        $this->assign("regione3id",$_POST['regione3']);
        $this->assign("regione4id",$_POST['regione4']);
        $this->assign("xiaozulist",$xiaozulist);
        $this->display();
    }

    
    public function ShowImages(){
        $this->LoginTrue();
        $stId=$_GET["stId"];
        $staffShow=M("staff");
        $rs_staffShow=$staffShow->where("stId={$stId}")->find();
        $this->assign("rs_staffShow",$rs_staffShow);
        
        //算年龄
        $nowTime=time();
        $year=date("Y");
        $staffShow_stBirthdate=strtotime($rs_staffShow["stBirthdate"]);
        $nowAge=floor(((($nowTime-$staffShow_stBirthdate)/86400)/365));
        $this->assign("nowAge",$nowAge);
       
        $this->display();
    }
    
    public function ShowFujian(){
        $this->LoginTrue();
        $stId=$_GET["stId"];
        $staffShow=M("staff");
        $rs_staffShow=$staffShow->where("stId={$stId}")->find();
        $this->assign("rs_staffShow",$rs_staffShow);
    
        //算年龄
        $nowTime=time();
        $year=date("Y");
        $staffShow_stBirthdate=strtotime($rs_staffShow["stBirthdate"]);
        $nowAge=floor(((($nowTime-$staffShow_stBirthdate)/86400)/365));
        $this->assign("nowAge",$nowAge);
         
        $this->display();
    }


    public function Del(){
        $this->LoginAreaAdmin();
        $this->LoginTrue();
        $stId=$_GET["stId"];
        $staffShow=M("staff");
        $rs_staffShow=$staffShow->where("stId={$stId}")->find();
        $this->assign("rs_staffShow",$rs_staffShow);
        $this->display();
    }
    public function DelAction(){
        $this->LoginAreaAdmin();
        $this->LoginTrue();
        $stId=$_GET["stId"];
        $staffShow=M("staff");
        $result=$staffShow->where("stId={$stId}")->delete();
        if($result){
            $this->success("删除成功",U("lists"));
        }else{
            $this->error("删除失败");
        }
    }
    public function DelAll(){
        $this->LoginAreaAdmin();
        $this->LoginTrue();
        $stId=$_POST["node"];
        $staff=M("staff");
        foreach($stId as $val){
            $result=$staff->where("stId={$val}")->delete();
        }
        $this->success("删除成功",U("lists"));
    }
    public function Update(){
        $this->LoginAreaAdmin();
        $this->LoginTrue();
        $stId=$_GET["stId"];
        $staffShow=M("staff");
        $variables=M("variables");
        $department=M("department");

        $rs_staffInfo=$staffShow->where("stId={$stId}")->find();//基本用户信息

        $regione1=session('regione1');
        $regione2=session('regione2');
        $regione3=session('regione3');
        $regione4=session('regione4');

        if(count($regione4)==1){
            $regioneid=$regione4[0]['id'];
            $xiaozulist=$department->field('dId,dName')->where("pId='{$regioneid}'")->select();
        }

        //下面对自定义变量的处理
        $rs_minzu = $variables->where("vId=5")->find();  //处理民族
        $minzuval=unserialize(stripslashes($rs_minzu["vVariablesVal"]));
        $minzu = $minzuval[LG];

        $this->assign("rs_staffInfo",$rs_staffInfo);
        $this->assign("minzu", $minzu);
        $this->assign("regione1", $regione1);
        $this->assign("regione2", $regione2);
        $this->assign("regione3", $regione3);
        $this->assign("regione4", $regione4);
        $this->assign("xiaozulist", $xiaozulist);

        $this->display();
    }
    public function UpdateAction(){
        $this->LoginAreaAdmin();
        $this->LoginTrue();
        $stId=$_GET["stId"];
        $staffAdd=M("staff");

        $data["stName"]=$_POST["stName"];
        $data["stSex"]=$_POST["stSex"];
        $data["stTel"]=$_POST["stTel"];
        $data["maisonNum"]=$_POST["maisonNum"];
        $data["nationNanme"]=$_POST["nationNanme"];
        $data["stMultiracial"]=$_POST["stMultiracial"];

        $IdCard=$data["stIDCard"]=$_POST["stIDCard"];
        if(!empty($data["stIDCard"])){
            $rs_stID=$staffAdd->where("stIDCard='{$IdCard}'")->find();
            if(!empty($rs_stID)&&$rs_stID['stId']!=$stId){
                $this->error("此身份证号码已经存在");
            }
        }

        if(!empty($_POST['xiaozu'])){
            $data["xiaozu"]=$_POST['xiaozu'];
            $data["regioneNum"]=$_POST['regione4'];
        }

        $result=$staffAdd->where("stId={$stId}")->save($data);
        if($result){
            $this->success("修改成功",U("lists"));
        }else{
            $this->error("修改失败");
        }
    }

	
    public function getxiaozuInfo(){
        $this->LoginTrue();
		$pId=$_POST["id"];
		$department=M("department");
		$regiones=$department->where("pId='$pId'")->select();
        echo json_encode($regiones);
	}

    /**
     * //导出考勤excel
     * $date = 考勤记录
     * $re_kabout=考勤类型数组
     */
    private function getExcel($date = array()){
        if(empty($date)){
            $this->error("查询结果为空，不能导出数据");
        }
        $regione=M("regione");
        $department=M("department");

        $objPHPExcel = new \PHPExcel();
        // set table header content
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '姓名')
            ->setCellValue('B1', '民语姓名')
            ->setCellValue('C1', '性别')
            ->setCellValue('D1', '身份证号')
            ->setCellValue('E1', '所属行政区')
            ->setCellValue('F1', '小组')
            ->setCellValue('G1', '房屋编号');

        foreach ($date as $k => $v) {
            $objPHPExcel->getActiveSheet(0)->setCellValue('A'.($k+2), $v['stName']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('B'.($k+2), $v['nationNanme']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('C'.($k+2),$v['stSex']=='1'?'男':'女');
            $objPHPExcel->getActiveSheet(0)->setCellValue('D'.($k+2), $v['stIDCard']);
            if(!empty($v['regioneNum']))
                $regioneinfo=$regione->where("id='{$v['regioneNum']}'")->find();
            $objPHPExcel->getActiveSheet(0)->setCellValue('E'.($k+2), $regioneinfo['name']);        //行政区
            if(!empty($v['xiaozu'])){
                $xiaozuinfo=$department->where("dId='{$v['xiaozu']}'")->find();
            }
            $objPHPExcel->getActiveSheet(0)->setCellValue('F'.($k+2), $xiaozuinfo['dName']);            //小组
            $objPHPExcel->getActiveSheet(0)->setCellValue('G'.($k+2), $v['maisonNum']);

        }

        // excel头参数
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="考勤表'.date('Y-m-d').'.xlsx"');  //日期为文件名后缀
        header('Cache-Control: max-age=0');

        ob_clean();//关键
        flush();//关键
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');  //excel5为xls格式，excel2007为xlsx格式
        $objWriter->save('php://output');
        exit;
    }
}